package com.umfwechat.h5.controller.gathering;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.RandomUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umfwechat.util.wx.SignUtil;
import com.umfwechat.wx.service.WeixinService;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
import com.umpay.sp.util.AmountUtil;
import com.umpay.sp.xml.XmlData;
import com.umpay.util.HttpUtil;

/**
 * @desc  收款模块
 * @author Wangzhilong
 * @date 2017-5-11 下午7:41:12
 */
@Controller
@RequestMapping("/h5/gathering")
public class GatheringController {

    private static Logger logger = LoggerFactory.getLogger(GatheringController.class);
	
	@Resource
	private UserServiceRemote userServiceRemote_sp; 
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote; 
	//店铺部署接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemot;
	//调用微信接口
	@Resource
	private WeixinService weixinService;
	
	
	/**
	 * 获取调用扫一扫签名
	 * @param targetUrl 路径
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/both/getSignture",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String getSignture(String targetUrl,HttpServletRequest request) {
		logger.info("获取调用扫一扫签名====开始=====>>>>>>|GatheringController|getSignture");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//获取微信jssdk---ticket
	    String jsapi_ticket = weixinService.getJSSDKTicket();
		//时间戳
        String timeStamp=SignUtil.create_timestamp();
        //随机字符串
        String nonceStr=SignUtil.CreateNoncestr();
        
        SortedMap<Object,Object> signParams = new TreeMap<Object,Object>();  
        signParams.put("noncestr",nonceStr);  
        signParams.put("jsapi_ticket",jsapi_ticket);  
        signParams.put("timestamp", timeStamp);  
        signParams.put("url", targetUrl); //访问路径
        
        // 采用原始值进行SHA1算法！  
        logger.info("nonceStr="+nonceStr+"%%%jsapi_ticket="+jsapi_ticket+"%%%%timeStamp="+timeStamp+"%%%targetUrl"+targetUrl+"%%%%%%%");
       // String sign= SignUtil.createSign(signParams);
        String sign = SignUtil.getSignature(jsapi_ticket, timeStamp, nonceStr,targetUrl);
        logger.info("签名"+sign+"%%%%%%%%%%%%");
        //获取为微信公众号appid
        String APPID2 = PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("saas.wx.appid");
        
        //将数据传到前台
        resultMap.put("retCode",RetCode.SUCCESS);
        resultMap.put("retMsg","获取签名成功");
        resultMap.put("noncestr", nonceStr);
        resultMap.put("timestamp", timeStamp);
        resultMap.put("signature", sign);
        resultMap.put("appId",APPID2);
        
        logger.info("获取调用扫一扫签名====结束=====>>>>>>|GatheringController|getSignture");
        return JSONObject.fromObject(resultMap).toString();
    }
	
	
	/**
	 * 收款页面初始化
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/both/getStoreGathering",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String getStoreGathering(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("收款页面初始化接口开始|GatheringController|getStoreGathering");
		String openid="";
		if(request.getSession().getAttribute("openid") != null){
			openid = request.getSession().getAttribute("openid").toString();//获取openid
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		
		if(StringUtil.isEmpty(openid)){
			resultMap.put("retCode",RetCode.FAIL);
	        resultMap.put("retMsg","openid获取失败！");
			logger.info("从session中获取openid获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		
		try{
			//根据opendi查询第三方网站用户的用户编号
			ReqMessage req1 = ReqMessageUtil.makeSpReq();
			req1.getReqMap().put("externaluserId", openid);
			
			logger.info("查询第三方网站用户接口开始 ：【1】【1】【1】【1】req1=" + req1);
		    ResMessage res1 = userServiceRemote_sp.queryUserBind(req1);
			logger.info("查询第三方网站用户接口结束 ：【1】【1】【1】【1】resMessage=" + res1);

			if(!res1.getRetCode().equals(RetCode.SUCCESS)){ //判断res1
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", res1.getRetMsg());
				logger.info("查询第三方网站用户接口 失败:【失败】 "+res1);
				return JSONObject.fromObject(resultMap).toString();
			}
			//boolean empty = StringUtil.isEmpty((String)res1.getResMap().get("userId"));
			if(StringUtil.isEmpty(StringUtil.trim(res1.getValue("userId")))){//未取到用户编号
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","未获取到用户编号");
				logger.info("查询第三方网站用户接口 失败 ：【未获取到用户编号】" +res1);
				return JSONObject.fromObject(resultMap).toString();
			}
			String userId = res1.getResMap().get("userId").toString();//用户编号
			
			//根据主键userId查询用户详情接口
			ReqMessage req2 = ReqMessageUtil.makeSpReq();
			req2.getReqMap().put("userId", userId);
			logger.info("查询用户详情接口开始 ：【2】【2】【2】【2】req2=" + req2);
			ResMessage res2 = userServiceRemote_sp.getUserByIdSaaS(req2);
			logger.info("查询用户详情接口结束 ：【2】【2】【2】【2】resMessage=" + res2);
			//判断查询用户详情是否成功
			if(!res2.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg",res2.getRetMsg());
				logger.info("查询用户详情接口 失败：【失败】" +res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			//获取用户详情
			Map<String,Object> map =(Map<String,Object>)res2.getValue("merUser");
			String mediaId = map.get("merId").toString();//用户商户
			if(mediaId==null||"".equals(mediaId)){//未取到商户号
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","未取到商户号");
				logger.info("查询用户详情接口 失败：【未取到商户号】"+res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			if(!"0".equals(map.get("state").toString())){//用户不可用
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","用户不可用号");
				logger.info("查询用户详情接口 失败：【用户不可用号】" +res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			
			String rank = map.get("rank").toString();//角色
			StoreInf storeInf=null;
			if(rank.equals("1")){
				logger.info("此用户为收银员 ：=====++++++=====" +rank);
				
				//店铺部署详情接口
				ReqMessage req3 = ReqMessageUtil.makeSpReq();
				req3.getReqMap().put("storeId", mediaId);
				logger.info("店铺部署详情接口开始 ：【3】【3】【3】【3】req3=" + req3);
				ResMessage res3 = storeInfServiceRemot.getStoreInfByPri(req3);
				logger.info("店铺部署详情接口结束 ：【3】【3】【3】【3】resMessage=" + res3);
				//获取店铺详情失败
				if(!res3.getRetCode().equals(RetCode.SUCCESS)){
					resultMap.put("retCode",RetCode.FAIL);
			        resultMap.put("retMsg","获取店铺失败");
					logger.info("店铺部署详情接口失败  ：【res3】【失败】" +res3.getRetMsg());
					return JSONObject.fromObject(resultMap).toString();
				}
				//获取店铺简称信息
				storeInf =(StoreInf)res3.getResMap().get("storeInf");
				//信息传到前台
				result.put("storeId",storeInf.getStoreId());
				result.put("storeShortName",storeInf.getStoreShortName());
				result.put("merId",storeInf.getMerId());
				
				resultMap.put("retCode",RetCode.SUCCESS);
		        resultMap.put("retMsg",res3.getRetMsg());
		        resultMap.put("storeVo",result);
				//return JSONObject.fromObject(resultMap).toString();
			}else if(rank.equals("0")){
				logger.info("此用户为收款人 ：=====++++++=====" +rank);
				
				//店铺部署详情列表接口
				ReqMessage req4 = ReqMessageUtil.makeSpReq();
				req4.getReqMap().put("merId", mediaId);
				req4.getReqMap().put("defultStore","0");//默认店铺标识
				logger.info("店铺部署详情列表接口开始 ：【4】【4】【4】【4】req4=" + req4);
				ResMessage res4 = storeInfServiceRemot.getStoreInfList(req4);
				logger.info("店铺部署详情列表接口结束 ：【4】【4】【4】【4】resMessage=" + res4);
				if(!res4.getRetCode().equals(RetCode.SUCCESS)){
					resultMap.put("retCode",RetCode.FAIL);
			        resultMap.put("retMsg","查询店铺失败");
					logger.info("店铺部署详情列表接口失败 ：【res4】【失败】"+res4.getRetMsg());
					return JSONObject.fromObject(resultMap).toString();
				}
				String totalSize = res4.getResMap().get("totalSize").toString();//店铺数量
				if("0".equals(totalSize)){
					resultMap.put("retCode",RetCode.FAIL);
			        resultMap.put("retMsg","用户未选择默认店铺店铺");
					logger.info("店铺部署详情列表接口 ：【res4】【用户未选择默认店铺店铺】");
					return JSONObject.fromObject(resultMap).toString();
				}
				if(Integer.parseInt(totalSize)>1){
					resultMap.put("retCode",RetCode.FAIL);
			        resultMap.put("retMsg","用户有多个默认店铺店铺");
					logger.info("店铺部署详情列表接口 ：【res4】【用户有多个默认店铺店铺】");
					return JSONObject.fromObject(resultMap).toString();
				}
				// 读取店铺部署详情列表中的店铺列表
				List<StoreInf> list = (List<StoreInf>)res4.getValue("storeInfList");
				//取出默认店铺信息
				storeInf = list.get(0);
				//信息传到前台
				result.put("storeId",storeInf.getStoreId());
				result.put("storeShortName",storeInf.getStoreShortName());
				result.put("merId",storeInf.getMerId());
				resultMap.put("retCode",RetCode.SUCCESS);
		        resultMap.put("retMsg",res4.getRetMsg());
		        resultMap.put("storeVo",result);
				
				//return JSONObject.fromObject(resultMap).toString();
			}else{
				resultMap.put("retCode",RetCode.FAIL);
		        resultMap.put("retMsg","此用户不属于任何角色");
		        return JSONObject.fromObject(resultMap).toString();
			}
			
			String productId_add = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY_ADDED);
			String productId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY);
			// 渠道开通列表返回查询接口
			ReqMessage req5 = ReqMessageUtil.makeSpReq();
			req5.getReqMap().put("appSysId",storeInf.getStoreId());
			req5.getReqMap().put("productIds","'"+productId+"','"+productId_add+"'");
			logger.info("根据主键查询渠道表开始 ：【5】【5】【5】【5】req5 = " + req5);
			ResMessage res5 =appChannelServiceRemote.getAppChannelListByProductids(req5);
			logger.info("根据主键查询渠道表结束 ：【5】【5】【5】【5】res5 = " + res5);
			
			if (!res5.getRetCode().equals(RetCode.SUCCESS)) {
				resultMap.clear();
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","渠道开通列表查询失败");
				logger.info("查询渠道开通接口失败 ：【res5】【失败】 " + res5.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			//获取查询到的渠道信息
			List<AppChannel> appChannellist = (List<AppChannel>)res5.getValue("appChannelList");
			if(null==appChannellist||appChannellist.isEmpty()){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","渠道开通列表查询为空");
				logger.info("渠道开通列表查询为空");
				return JSONObject.fromObject(resultMap).toString();
			}
			AppChannel appChannel = appChannellist.get(0);
			//应用编号（店铺id）对应一个主产品号
			if (appChannel.getState().equals(4)) {
				logger.info("判断该店铺渠道开通为未签约状态===【】【】=====【】【】=====");
				resultMap.clear();
				resultMap.put("retCode",RetCode.FAIL);
		        resultMap.put("retMsg","此店铺未签约立马付产品");
				return JSONObject.fromObject(resultMap).toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("==★★★★★=收款页面初始化异常，操作失败："), e);
			resultMap.clear();
			resultMap.put("retCode",RetCode.UNKNOWN);
	        resultMap.put("retMsg","收款页面初始化异常！");
		}
		logger.info("收款页面初始化接口结束===========>>>>>>>|GatheringController|getStoreGathering");
		return JSONObject.fromObject(resultMap).toString();
	}
	
	/**
	 * 收款支付
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/both/gathering",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String gathering(String storeId,String storeShortName,String merId,String amount,String authCode,HttpServletRequest request) throws Exception{		
		logger.info("收款支付接口开始=====开始=====>>>>>>|GatheringController|gathering");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> res = new HashMap<String, Object>();
		String productName=null;//支付类型
		//通知地址
		String notifyurl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","notifyurl", "");
		//扫码支付被扫接口
		String url = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","qrcode.saas.pay", "");
		try{
			
			Map<String, Object> params = new HashMap<String, Object>();
			ReqMessage r = ReqMessageUtil.makeSpReq();
			String rpid = r.getRpid();
			params.put("rpid", rpid);
			String ord = RandomUtil.getRandomNum(10); //订单号
			StringBuffer buffer = new StringBuffer();
			buffer.append(storeId);
			buffer.append(r.getReqDate());
			buffer.append(ord);
			String orderId = buffer.toString();//订单号
			logger.info("=============//订单号========" + orderId);
			params.put("orderId",orderId);
			params.put("orderDate",r.getReqDate());//订单日期
			params.put("merDate",r.getReqDate());//交易日期
			params.put("merId", storeId);// 商户号
			logger.info("=========金额============" + amount);
			double d = Double.parseDouble(amount);
			logger.info("========金额Double=============" + d);
			int s=(int)(d*100);
			logger.info("======金额int===============" + s);
			params.put("amount",s+"");// 金额
			params.put("oriAmount",s+"");// 原单金额
			params.put("amtType", "01");// 金额类型
			params.put("retUrl", "");//商户前台地址
			params.put("notifyUrl",notifyurl);// 后台通知地址
			String su =null;
			if(StringUtil.isNotEmpty(authCode)){ //授权码
				su = authCode.substring(0,2);
			}
			if(su.equals("10")||su.equals("11")||su.equals("12")||su.equals("13")||su.equals("14")||su.equals("15")){
				String productId = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId.saas.weChatBarCode", "");
				String bankId = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","bankId.saas.weChatBarCode", "");
				params.put("productId",productId);// 微信条码支付API产品号
				productName="微信";
				params.put("useDesc",storeShortName);// 
				params.put("bankId",bankId);// 通道编号
			}else{
				String productId = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId.saas.alipayBarCode", "");
				String bankId = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","bankId.saas.alipayBarCode", "");
				params.put("productId",productId);// 支付宝条码支付API产品号
				productName="支付宝";
				params.put("useDesc",storeShortName);// 
				params.put("bankId",bankId);// 通道编号
			}
			params.put("authCode", authCode);// 授权码
			params.put("goodsInf",storeShortName);//商品描述
			
			params.put("instId","20000001");
			params.put("trace","37052218422990311");
			params.put("merCheckDate",r.getReqDate());//商户对账日期
			params.put("version","4.0");//版本号
			params.put("payDate",r.getReqDate());//支付日期
			params.put("notifyData",r.getReqDate());
			String addr = request.getRemoteAddr();
			params.put("userUmpIp",addr);
			params.put("userMerIp",addr);
			params.put("userIp",addr);
			params.put("orderIp",addr);
			params.put("title",storeShortName);
			params.put("funCode",r.getReqDate());
			Date nowDate = new Date();
			String date=DateTimesUtil.formatDate(nowDate,DateTimesUtil.formatTime18Str);
			
			logger.info("扫码支付被扫接口 ：%%%%%%%%%%%开始%%%%%%%%%%%输入参"+params+"&&&&&&&&url==="+url);
			res = HttpUtil.httpPostForm2Xml(url, params,"GBK");
			logger.info("扫码支付被扫接口 ：%%%%%%%%%%%结束%%%%%%%%%%%输出参"+res);
			//交易单号
			String tradeNo = res.get("tradeNo").toString();
			String retCode = res.get("retCode").toString();//返回码
			String merDate = res.get("merDate").toString();//交易日期
			if(!retCode.equals(RetCode.SUCCESS)){
				if(retCode.equals("00200014")){
					resultMap.put("retMsg","需用户确认");
				}else{
					resultMap.put("retMsg","支付失败");
					logger.info("扫码支付被扫失败 【】【retMsg】：%%%%%%%%%%%失败%%%%%%%%%%%");
				}
				resultMap.put("retCode", RetCode.FAIL);
				return JSONObject.fromObject(resultMap).toString();
			}
			//订单号
			String orderId1 = res.get("orderId").toString();
			//把从redis中获取订单
			String string2 = RedisUtil.get(CacheConsts.WX+"orderId"+orderId1);
			if(StringUtil.isNotEmpty(string2)&&string2.equals(orderId1)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "已收款成功");
				return JSONObject.fromObject(resultMap).toString();
			}
			
			//把订单存入redis
			RedisUtil.set(CacheConsts.WX+"orderId"+orderId1, 86400, orderId1);
			
	        String string = res.get("amount").toString();
			String dollar2 = AmountUtil.Cent2Dollar2(string);
			
			logger.info("用户列表查询(此店铺下的所有收银员)(发送模板)：%%%%%%%%%%%!!!!!!!!!!%%%%%%%%%%");
			//用户列表查询(此店铺下的所有收银员)
			ReqMessage req2 = ReqMessageUtil.makeSpReq();
			req2.getReqMap().put("merFlag", storeId);
			req2.getReqMap().put("state", "0");
			req2.put("currentPage", String.valueOf(1));
			
			req2.put("pageSize", String.valueOf(100));
			logger.info("用户列表查询接口开始 【1】【1】【1】【1】req2====="+req2);
		    ResMessage res2 = userServiceRemote_sp.queryList(req2);
			logger.info("用户列表查询接口结束 ：【1】【1】【1】【1】resMessage=" + res2);
			List<Map<String, Object>> resultList = (List<Map<String, Object>>)res2.getResMap().get(XmlData.RESULT_LIST);
			//查询出的用户数量
			String totalSize = res2.getResMap().get(XmlData.TOTAL_SIZE).toString();
			if(!totalSize.equals("0")&&!"0".equals(totalSize)){
				for(Map<String, Object> objMap : resultList){
					//给收银员发送模板消息
					this.sendTemplate(objMap,resultMap,orderId,tradeNo,amount,storeShortName,productName,productName);
				}
			}
			logger.info("用户列表查询(此店铺下的收款人)(发送模板)：%%%%%%%%%%%!!!!!!!!!!%%%%%%%%%%");
			
			//用户列表查询(此店铺下的收款人)
			ReqMessage req3 = ReqMessageUtil.makeSpReq();
			req3.getReqMap().put("merFlag", merId);
			req3.getReqMap().put("state", "0");
			req3.put("currentPage", String.valueOf(1));
			req3.put("pageSize", String.valueOf(100));
			logger.info("用户列表查询接口开始 【1】【1】【1】【1】req3==="+req3);
		    ResMessage res3 = userServiceRemote_sp.queryList(req3);
			logger.info("用户列表查询接口结束 ：【1】【1】【1】【1】resMessage=" + res3);
			List<Map<String, Object>> resultList3 = (List<Map<String, Object>>)res3.getResMap().get(XmlData.RESULT_LIST);
			//查询出的用户数量
			String totalSize3 = res3.getResMap().get(XmlData.TOTAL_SIZE).toString();
			if(!totalSize3.equals("0")&&!"0".equals(totalSize3)){
				Map<String, Object> map = resultList3.get(0);
				//给收款人发模板消息
				this.sendTemplate(map, resultMap, orderId,tradeNo, amount, storeShortName, productName,productName);
			}
			
			//传给前台
			result.put("merId",res.get("merId"));
			result.put("merDate",res.get("merDate"));
			result.put("amount",dollar2);
			result.put("orderId",res.get("orderId"));
			result.put("productName",productName);
			resultMap.put("retCode", RetCode.SUCCESS);
			resultMap.put("retMsg", "支付成功");
			resultMap.put("orderVo",result);
			logger.info("收款支付接口开始=====结束=====>>>>>>|GatheringController|gathering");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("==★★★★★=收款支付接口异常，操作失败："), e);
			resultMap.put("retCode",RetCode.UNKNOWN);//请求失败，设置回参
			resultMap.put("retMsg","收款失败！");
		}
	
		return JSONObject.fromObject(resultMap).toString();
	}
	
	
	/**
	 * 发送模板消息
	 * @param objMap
	 * @param resultMap
	 * @param orderId
	 * @param amount
	 * @param storeShortName
	 * @param productName
	 */
	public void sendTemplate(Map<String, Object> objMap,Map<String, Object> resultMap,String orderId,String tradeNo,String amount,String storeShortName,String merDate,String productName){
		//查询第三方网站用户接口
		ReqMessage req3 = ReqMessageUtil.makeSpReq();
		String userId = objMap.get("userId").toString();
		req3.getReqMap().put("userId", userId);
		req3.getReqMap().put("state","2");
		logger.info("查询第三方网站用户接口 开始：【2】【2】【2】【2】req3 = " + req3);
		ResMessage res3 = userServiceRemote_sp.queryUserBind(req3);
		logger.info("查询第三方网站用户接口结束 ：【2】【2】【2】【2】resMessage = " +res3);
		if(res3.getRetCode().equals(RetCode.SUCCESS)){
			//获取第三方的openid
			String openid = res3.getResMap().get("externalUserId").toString();
			if(StringUtil.isNotEmpty(openid)){
				//后台通知地址
				String template = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saas.template.inform", "");
				StringBuffer buffer = new StringBuffer(template);
				buffer.append(tradeNo);
				buffer.append("&tradingStore=");
				buffer.append(storeShortName);
				//模板Id
				String templateId2 = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saas.wx.templateId2", "");
				//发送支付模板消息
				Map<String,String> map= new HashMap<String,String>();
				map.put("template_id",templateId2);
				map.put("openid",openid);
				map.put("url",buffer.toString());
				map.put("keyword1",orderId);
				map.put("keyword2",amount);
				map.put("keyword3",storeShortName);
				map.put("keyword4",merDate);
				map.put("keyword5",productName);
				logger.info("发送模板消息接口开始=======WeixinServiceImpl===sendTemplateMessage===");
				try {
					boolean b = weixinService.sendTemplateMessage1(map);
				    if(b){
				    	resultMap.put("retCode", RetCode.SUCCESS);
						resultMap.put("retMsg", "支付成功-发送模板消息成功");
						logger.info("发送模板消息接口开始=======WeixinServiceImpl===sendTemplateMessage==支付成功-发送模板消息成功=");
				    }else{
				    	resultMap.put("retCode", RetCode.SUCCESS);
						resultMap.put("retMsg", "支付成功-发送模板消息失败");
						logger.info("发送模板消息接口开始=======WeixinServiceImpl===sendTemplateMessage==支付成功-发送模板消息失败=");
				    }
				} catch (Exception e) {
					resultMap.put("retCode", RetCode.SUCCESS);
					resultMap.put("retMsg", "发送模板消息异常");
					logger.info("发送模板消息接口开始=======WeixinServiceImpl===sendTemplateMessage==发送模板消息异常=");
					   
				}
				
			}
		}
	}
	
	/**
	 * 主扫通知
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/both/gathering/inform",produces="application/json;charset=UTF-8")
	public void inform(HttpServletRequest request,HttpServletResponse response,ReqMessage req) throws Exception{	
		
		logger.info("主扫通知接口开始=========>>>>>>|GatheringController|inform");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//获取值
			String merId = request.getParameter("mer_id");//商户号
			String sign = request.getParameter("sign");//签名方式
			String signType = request.getParameter("sign_type");//签名
			String version = request.getParameter("version");//版本号
			String orderId = request.getParameter("order_id");//订单号
			String merDate = request.getParameter("mer_date");//订单日期
			String amount = request.getParameter("amount");//付款金额
			String payType = request.getParameter("pay_type");//支付方式
			String payDate = request.getParameter("pay_date");//支付日期
			String tradeNo = request.getParameter("trade_no");//交易订单
			String retCode1 = request.getParameter("error_code");//返回码
			String productName="扫码支付";
			logger.info("mer_id="+merId+"&sign_type="+signType+"&sign="+sign+"&version="+version+"&order_id="+orderId+"&mer_date="+merDate+"&ret_code="+retCode1);
			
			String retCode="0000";
			String content="mer_id="+merId+"&sign_type="+signType+"&sign="+sign+"&version="+version+"&order_id="+orderId+"&mer_date="+merDate+"&ret_code="+retCode;
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			String outStr = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><META NAME=\"MobilePayPlatform\"  CONTENT=\""+content+"\" /></head><body></body></html> ";
		    logger.info(outStr);
			out.write(outStr);
			out.close();
			
			
	        if(!retCode1.equals(RetCode.SUCCESS)){
	        	logger.info("主扫通知=======交易是失败=>>>");
			}else{
				Thread.sleep(1000);
				String dollar2 = AmountUtil.Cent2Dollar2(amount);
				
				String string2 = RedisUtil.get(CacheConsts.WX+"orderId"+orderId);
				logger.info("主扫通知=======从redis中取出订单===>>>orderId"+string2);
				if(StringUtil.isEmpty(string2)||!string2.equals(orderId)){
					RedisUtil.set(CacheConsts.WX+"orderId"+orderId,86400,orderId);
					//店铺部署详情接口
					ReqMessage req1 = ReqMessageUtil.makeSpReq();
					req1.getReqMap().put("storeId", merId);
					logger.info("店铺部署详情接口开始 ：req1=" + req1);
					ResMessage res1 = storeInfServiceRemot.getStoreInfByPri(req1);
					logger.info("店铺部署详情接口结束 ：resMessage=" + res1);
					//获取店铺详情失败
					if(!res1.getRetCode().equals(RetCode.SUCCESS)){
						logger.info("店铺部署详情接口失败  ：" +res1.getRetMsg());
					}
					logger.info("获取店铺简称");
					StoreInf storeInf =(StoreInf)res1.getResMap().get("storeInf");
					String storeShortName = storeInf.getStoreShortName();
					logger.info("用户列表查询(此店铺下的所有收银员)(发送模板)：%%%%%%%%%%%!!!!!!!!!!%%%%%%%%%%");
					
					//用户列表查询(此店铺下的所有收银员)
					ReqMessage req2 = ReqMessageUtil.makeSpReq();
					req2.getReqMap().put("merFlag", merId);
					req2.getReqMap().put("state", "0");
					req2.put("currentPage", String.valueOf(1));
					req2.put("pageSize", String.valueOf(100));
					logger.info("用户列表查询接口开始 【1】【1】【1】【1】req2==="+req2);
				    ResMessage res2 = userServiceRemote_sp.queryList(req2);
					logger.info("用户列表查询接口结束 ：【1】【1】【1】【1】resMessage=" + res2);
					List<Map<String, Object>> resultList = (List<Map<String, Object>>)res2.getResMap().get(XmlData.RESULT_LIST);
					//查询出的用户数量
					String totalSize = res2.getResMap().get(XmlData.TOTAL_SIZE).toString();
					if(!totalSize.equals("0")&&!"0".equals(totalSize)){
						for(Map<String, Object> objMap : resultList){
							//给收银员发送模板消息
							this.sendTemplate(objMap, resultMap, orderId,tradeNo, dollar2, storeShortName,"",productName);
						}
					}
					
					logger.info("用户列表查询(此店铺下的收款人)(发送模板)：%%%%%%%%%%%!!!!!!!!!!%%%%%%%%%%");
					
					String merId1 = storeInf.getMerId();//店铺 的主商户
					//用户列表查询(此店铺下的收款人)
					ReqMessage req3 = ReqMessageUtil.makeSpReq();
					req3.getReqMap().put("merFlag", merId1);
					req3.getReqMap().put("state", "0");
					req3.put("currentPage", String.valueOf(1));
					req3.put("pageSize", String.valueOf(100));
					logger.info("用户列表查询接口开始 【1】【1】【1】【1】req3==="+req3);
				    ResMessage res3 = userServiceRemote_sp.queryList(req3);
					logger.info("用户列表查询接口结束 ：【1】【1】【1】【1】resMessage=" + res3);
					List<Map<String, Object>> resultList3 = (List<Map<String, Object>>)res3.getResMap().get(XmlData.RESULT_LIST);
					//查询出的用户数量
					String totalSize3 = res3.getResMap().get(XmlData.TOTAL_SIZE).toString();
					if(!totalSize3.equals("0")&&!"0".equals(totalSize3)){
						Map<String, Object> map = resultList3.get(0);
						//给收款人发模板消息
						this.sendTemplate(map,resultMap,orderId,tradeNo,dollar2,storeShortName,"",productName);
					}
					
				}
				
			}
			logger.info("主扫通知====结束==================>>>");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("==★=主扫通知接口异常，操作失败："), e);
		}
	}
	
}
